package com.example.aicooking.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aicooking.entity.CookingStep;
import com.example.aicooking.entity.vo.CookingStepVO;
import com.example.aicooking.mapper.CookingStepMapper;
import com.example.aicooking.service.CookingStepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CookingStepServiceImpl implements CookingStepService {
    @Autowired
    private CookingStepMapper cookingStepMapper;

    @Override
    public List<CookingStepVO> getStepsByWorksId(Long worksId) {
        List<CookingStep> steps = cookingStepMapper.findByWorksId(worksId);
        return steps.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void saveSteps(Long worksId, List<CookingStepVO> steps) {
        // 先删除原有步骤
        QueryWrapper<CookingStep> wrapper = new QueryWrapper<>();
        wrapper.eq("works_id", worksId);
        cookingStepMapper.delete(wrapper);

        // 保存新步骤
        for (int i = 0; i < steps.size(); i++) {
            CookingStepVO stepVO = steps.get(i);
            CookingStep step = new CookingStep();
            step.setWorksId(worksId);
            step.setStepNumber(i + 1);
            step.setDescription(stepVO.getDescription());
            step.setPhotoUrl(stepVO.getPhotoUrl());
            cookingStepMapper.insert(step);
        }
    }

    private CookingStepVO convertToVO(CookingStep step) {
        CookingStepVO vo = new CookingStepVO();
        vo.setStepNumber(step.getStepNumber());
        vo.setDescription(step.getDescription());
        vo.setPhotoUrl(step.getPhotoUrl());
        return vo;
    }
}
